package com.lans.linear;

import java.util.Iterator;

/**
 * @author: lans
 * @date: 2025/2/24
 * @name: 刘宇
 */
public class Queue<T> implements Iterable<T> {
    private Node head;
    private Node first;
    private Node last;
    private int N;

    public Queue() {
        head = new Node(null,null);
        last = null;
        N=0;
    }

    @Override
    public Iterator<T> iterator() {
        return new MyIterator();
    }
    private class MyIterator implements Iterator<T>{
        private Node n = head;

        @Override
        public boolean hasNext() {
            return n.next !=null;
        }

        @Override
        public T next() {
            //获取当前节点
            Node node = n.next;
            n = n.next;
            return node.item;
        }
    }


    public boolean isEmpty(){
        return N==0;
    }
    public int size(){
        return N;
    }
    //从队列中拿出一个元素
    public T dequeue(){
        if(isEmpty()){
            return null;
        }
        Node oldFirst = head.next;
        head.next = oldFirst.next;
        N--;
        if (isEmpty()) {
            last = null ;
        }
        return oldFirst.item;
    }
    //往队列中插入一个元素
    public void enqueue(T t){
        if(last==null){
            last = new Node(t,null);
            head.next = last;
        }else{
            Node oldLast = last;
            last = new Node(t,null);
            oldLast.next = last;
        }
        N++;
    }

    private class Node{
        private T item;
        private Node next;

        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        Queue<String> queue = new Queue<>();
        queue.enqueue("马云");
        queue.enqueue("马化腾");
        queue.enqueue("马英睿");
        queue.enqueue("马牛逼");
        for(String str:queue){
            System.out.println(str);
        }
    }
}
